import { AfterViewInit, ChangeDetectionStrategy, Component } from '@angular/core';
import { MatSnackBar } from '@angular/material/snack-bar'
import { Clipboard } from '@angular/cdk/clipboard'
import { Observable } from 'rxjs'
import { map } from 'rxjs/operators'

import { IpcService } from './service/ipc.service'

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class AppComponent implements AfterViewInit {
  title = 'jets';

  update$: Observable<string>
  codes$: Observable<any[]>

  constructor(private ipcService: IpcService, private clipboard: Clipboard, private snackBar: MatSnackBar) {
    this.update$ = this.ipcService.reply$.pipe(
      map(([resp]) => {
        return resp?.updateDate
      })
    )
    this.codes$ = this.ipcService.reply$.pipe(
      map(([resp]) => {
        return resp?.codes || []
      })
    )
  }

  ngAfterViewInit(): void {
    this.ipcService.send()
  }

  copyToClipboard(entry: any): void {
    const {name, content} = entry
    const r = this.clipboard.copy(content)
    if (r) {
      this.snackBar.open(`已复制: ${entry.name}`, null, {duration: 3000})
    }
  }
}
